<script setup lang="ts">
import { ref } from 'vue'
import { getAddPatientApi, patientDetailApi, updatePatientApi } from '@/api/patien'
import type { PatientParams } from '@/types/patien'
import { onLoad } from '@dcloudio/uni-app'
interface Props {
  id: string
}
const isLoading = ref(false)
// 接收路由参数
const props = defineProps<Props>()
//1.定义表单数据
const formData = ref<PatientParams>({
  name: '小明',
  idCard: '360733200205283619',
  gender: 1, // 1:男, 0:女
  defaultFlag: 1,
})

//2.创建ref数据v-model绑定数据
const formRef = ref<UniHelper.UniFormsInstance>()

//3.设置表单校验规则
const fromRules: UniHelper.UniFormsRules = {
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, errorMessage: '患者姓名位2-5位中文' },
    ]
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写患者身份证' },
      {
        pattern: /^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
        errorMessage: '身份证号码有问题',
      },
    ]
  },
  gender: {
    rules: [
      {
        validateFunction: (rule, value, data, callback) => {
          const sexNum = Number(formData.value.idCard.charAt(16))
          // 奇数为男  偶数位女
          const isGenderMatch = sexNum % 2 === value % 2
          return isGenderMatch || callback('性别与身份证号码不匹配')
        },
      }
    ]
  },
}

//4.触发表单校验提交到服务器
let onSubmit = async () => {

  try {
    await formRef.value?.validate!()

    isLoading.value = true
    // 判断是否更新
    if (props.id) {
      // 更新患者接口
      await updatePatientApi(formData.value)
    } else {
      // 添加患者接口
      await getAddPatientApi(formData.value)
    }
    await uni.showToast({
      title: props.id ? '更新成功!' : '添加成功',
      icon: 'success'
    })
    isLoading.value = false
    // 返回上一页
    uni.navigateBack()
  } catch (error) {
    uni.showToast({
      title: error.message,
      icon: 'none'
    })
  }
}

//判断是否编辑
onLoad(async () => {
  //如果没有id就返回
  if (!props?.id) return
  uni.setNavigationBarTitle({ title: '编辑患者' })
  //请求数据更新表单
  const res = await patientDetailApi(props.id)
  formData.value = {
    name: res.name,
    idCard: res.idCard,
    gender: res.gender, // 1:男, 0:女
    defaultFlag: res.defaultFlag,
    id: props.id,
  }
}) 
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :rules="fromRules" :model="formData">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput placeholder-style="color: #C3C3C5; font-size: 32rpx" :style="{ color: '#121826' }"
            :input-border="false" :clearable="false" placeholder="请填写真实姓名" v-model="formData.name" />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput placeholder-style="color: #C3C3C5; font-size: 32rpx" :style="{ color: '#121826' }"
            :input-border="false" :clearable="false" placeholder="请填写身份证号" v-model="formData.idCard" />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox mode="tag" selectedColor="#16C2A3" :localdata="[
            { text: '男', value: 1 },
            { text: '女', value: 0 },
          ]" v-model="formData.gender" />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人">
          <view class="uni-switch">
            <!-- !! 表示强制转换 !!0 强制强化为false -->
            <switch :checked="!!formData.defaultFlag" @change="formData.defaultFlag = $event.detail.value ? 1 : 0"
              color="#20c6b2" style="transform: scale(0.7)" />
          </view>
        </uni-forms-item>
        <!-- 5.绑定校验方法 -->
        <button class="uni-button" :loading="isLoading" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
@import './form.scss';
</style>
